<?php
namespace app\api\controller;

use app\common\controller\Logined;
use app\common\service\BalanceService;
use app\common\service\TransferService;

use think\Db;

//转账
class Transfer extends Logined{


	/*
	获取转账列表
	 */
	public function getTransList(){
		$uid = $this->uid;
		if(empty($uid)){
			$this->retData(1,'缺少参数');
		}
		$data = model('TransferConfigModel')->transferList($uid);
		if($data){
			//获取钱包地址列表
			foreach ($data as $key => $val) {
				$data[$key]['address_list'] = Db::table('tp_coin')->alias('c')
											->join('tp_user_wallet_address a','a.cid=c.id and uid='.$uid,'LEFT')
											->where('c.wid',$val['wid'])
											->where('c.status',1)
											->order('c.sort asc')
											->field('c.id cid,c.name coin_name,a.address')
											->select();
			}
			$this->retData(0,'success',$data);
		} else {
			$this->retData(0,'fail');
		}
	}


	/*
	获取单个钱包转账
	 */
	public function getTransOne(){
		$uid = $this->uid;
		$wid = P('wid');
		if(empty($uid) || empty($wid)){
			$this->retData(1,'缺少参数');
		}
		$data = model('TransferConfigModel')->transOne($uid,$wid);
		if($data){
			$data['address_list'] = Db::table('tp_coin')->alias('c')
											->join('tp_user_wallet_address a','a.cid=c.id and uid='.$uid,'LEFT')
											->where('c.wid',$wid)
											->where('c.status',1)
											->field('c.id cid,c.name coin_name,a.address')
											->select();
			$this->retData(0,'success',$data);
		} else {
			$this->retData(0,'fail');
		}
	}

	public function transfer(){
		if(C('transfer_status') != 1){
			$this->retData(1,'转账功能维护中~~');
		}
		$uid        = $this->uid;
		$to_address = P('to_address');
		$id         = P('id');
		$amount     = P('amount');
		$paypass    = P('paypass')?:123456;
		$password   = P('password');
		if(empty($uid) || empty($to_address) || empty($id)  || empty($amount) || empty($paypass)){
			$this->retData(1,'缺少参数');
		}

		if($amount <= 0){
			$this->retData(1,'转账数量有误，请重新输入');
		}
		//配置是否存在
		$config = model('TransferConfigModel')->getOneConfig($id,$uid);

		if(empty($config)){
			$this->retData(1,'未找到提币配置');
		}
		if (md5($password) != $this->user_info['password']) {
            $this->retData(1,'密码错误');
        }

		if($amount < $config['min_amount']){
			$this->retData(1,'最低转账数量:'.$config['min_amount']);
		}
		if ($config['balance'] < $amount) {
			$this->retData(1,'余额不足');
		}
		if ($config['wid'] == $config['fee_wid']) {
			if($config['fee_type'] == 1){
				$fee           = $amount*$config['fee'];
			} else {
				$fee           = $config['fee'];
			}
			// $left_amount = $amount - $fee;
			// if ($left_amount<0) {
			// 	$this->retData(1,'手续费不足');
			// }
			$left_amount = $amount;
			if ($config['balance'] < $amount+$fee) {
			$this->retData(1,'手续费不足');
		}
		} else {
			$fee_balance = model('UserBalanceModel')->getBalance($uid,$config['fee_wid']);
			if($config['fee_type'] == 1){
				$fee           = $amount*$config['fee'];
			} else {
				$fee           = $config['fee'];
			}
			$left_amount = $amount;
			if ($fee_balance < $fee) {
				$this->retData(1,'手续费不足');
			}
		}
		Db::startTrans();
		$wid = $config['wid'];
		$dd = 0;
		if ($wid >= 10) {
			$to_info = model('WalletAddressModel')->getUidByAddress($config['wid'],$to_address);
			if (empty($to_info)) {
				$dd = 1;
				$to_uid = 0;
			} else {
				$to_uid = $to_info['uid'];
			}
		} else {
			$to_info = model('WalletAddressModel')->getUidByAddress($config['wid'],$to_address);

			$to_uid = $to_info['uid'];
			if(empty($to_info) || $to_uid==$uid){
				$this->retData(1,'收款钱包地址有误');
			} 
		}

		
		$from_address = model('WalletAddressModel')->getAddressByUid($uid,$wid)['address'];
		//添加转账记录
		$res1 = model('TransferRecordModel')->addRecord($uid,$to_uid,$wid,$amount,$left_amount,$config['fee_wid'],$fee);
		//转出
		$res2 = BalanceService::updateBalance($uid,$wid,-$left_amount,'转账',41,$res1,$to_address);
		if ($fee > 0) {
			$res3 = BalanceService::updateBalance($uid,$config['fee_wid'],-$fee,'转账手续费',43,$res1,$to_address);
		} else {
			$res3 = 1;
		}
		
		//收款
		if ($to_uid) {
			$res4 = BalanceService::updateBalance($to_uid,$wid,$left_amount,'转账',42,$res1,$from_address);
		} else {
			$res4 = 1;
		}
		
		
		//上链
		$res5 = $res6 = $res7 = 1;
		if ($wid >= 10) {
			switch ($wid) {
				case '10':
					$currency_id = 40;
					break;
				case '11':
					$currency_id = 41;
					break;
				case '12':
					$currency_id = 42;
					break;
				case '13':
					$currency_id = 43;
					break;
				default:
					# code...
					break;
			}
			$res6 = Db::table('log_buy')->insert([
				'user_id'=>0,
				'currency_id'=>$currency_id,
				'type'=>41,
				'change'=>$left_amount,
				'memo'=>'转账',
				'from_address'=>$from_address,
				'to_address'=>$to_address,
				'over_status'=>0,
				'create_time'=>date('Y-m-d H:i:s')
			]);
			if ($fee != 0) {
				$fee_address = C('system_fee_address');
				$res7 = Db::table('log_buy')->insert([
					'user_id'=>0,
					'currency_id'=>$currency_id,
					'type'=>41,
					'change'=>$fee,
					'memo'=>'转账手续费',
					'from_address'=>$from_address,
					'to_address'=>$fee_address,
					'over_status'=>0,
					'create_time'=>date('Y-m-d H:i:s')
				]);
			}
		}
		if ($wid < 10 && $config['fee_wid'] >= 10) {	
			switch ($config['fee_wid']) {
				case '10':
					$currency_id = 40;
					break;
				case '11':
					$currency_id = 41;
					break;
				case '12':
					$currency_id = 42;
					break;
				case '13':
					$currency_id = 43;
					break;
				default:
					# code...
					break;
			}
			if ($fee != 0) {
				$fee_address = C('system_fee_address');
				$res7 = Db::table('log_buy')->insert([
					'user_id'=>0,
					'currency_id'=>$currency_id,
					'type'=>41,
					'change'=>$fee,
					'memo'=>'转账手续费',
					'from_address'=>$from_address,
					'to_address'=>$fee_address,
					'over_status'=>0,
					'create_time'=>date('Y-m-d H:i:s')
				]);
			}
		}
		if($res1 && $res2 && $res3 && $res4 && $res5 && $res6 && $res7){
			if ($dd == 1) {
				//点点挖矿
				switch ($wid) {
		        	case '13':
		        		$balance_type = 1;
		        		break;
		        	case '10':
		        		$balance_type = 2;
		        		break;
		        	case '11':
		        		$balance_type = 3;
		        		break;
		        	case '12':
		        		$balance_type = 4;
		        		break;
		        	default:
		        		$balance_type = 2;
		        		break;
		        }
		        $time = time();
				$post_data = [
					't'=>$time,
					'sign'=>strtoupper(md5($time.'1AA9561F03B60FD1952173041982CA91')),
					'balance_type'=>$balance_type,
					'amount'=>$left_amount,
					'address'=>$to_address,
				];
				try{
					ini_set('default_socket_timeout',3);
					$res = curl('http://point.ifc005.com/api/interaction/topUp',$post_data);
					$res = json_decode($res,1);
					if ($res['success'] == false) {
						Db::rollback();
				   		$this->retData(1,'转账失败--点点');
					} 
				} catch (\Exception $e) {
					Db::rollback();
				   	$this->retData(1,'请求超时'.$e->getMessage());
				}
			}
			Db::commit();
			$this->retData(0,'转账成功');
		} else {
			Db::rollback();
			$this->retData(1,'转账失败');
		}
	}
}